package jh.com.jhappbf.ui;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.ab.util.AbJsonUtil;
import com.android.volley.Request.Priority;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import androidx.fragment.app.Fragment;
import jh.com.jhappbf.R;
import jh.com.jhappbf.fragmentactivity.MyFragmentActivity;
import jh.com.jhappbf.httputils.VolleyCallWebService;
import jh.com.jhappbf.httputils.VolleySingleton;
import jh.com.jhappbf.model.AssayModel;
import jh.com.jhappbf.utils.JsonHelper;

/**
 * @author Administrator
 */
public class AssayFragment extends Fragment {
    private ListView mListView;
    private List<AssayModel> mData = null;
    private MyBaseAdapter mAdapter = null;
    private ProgressBar mProgress;
    private TextView mTipView;
    private TextView mSetting1;
    private TextView mSetting2;

    //	private ImageView mRefresh;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.assay_list_view, null);
        findView(v);
        setListener();
        mData = new ArrayList<>();
        setAdapter();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        String value = format.format(new Date());
        getData(value, "");
        return v;
    }

    /**
     * 查找控件
     */
    private void findView(View v) {
/*		mRefresh =  (ImageView) getActivity().findViewById(R.id.ui_singleActivity_comeback);
		mRefresh.setImageResource(R.drawable.ic_refresh);
		mRefresh.setVisibility(View.VISIBLE);*/

        mListView = v.findViewById(R.id.ui_assay_listView);
        mProgress = v.findViewById(R.id.ui_assay_progress_bar);
        mTipView = v.findViewById(R.id.ui_assay_data_tip);


        mSetting1 = getActivity().findViewById(R.id.ui_singleActivity_txt1);
        mSetting2 = getActivity().findViewById(R.id.ui_singleActivity_txt2);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 1 && data != null) {
            String value = data.getStringExtra("date");
            if (value.length() > 0) {
                mSetting2.setText(value);
                String cargoname = mSetting1.getText().toString();
                if (!"货名".equals(cargoname)) {
                    getData(value, cargoname);
                } else {
                    getData(value, "");
                }
            }
        } else if (resultCode == 2 && data != null) {
            String value = data.getStringExtra("result");
            if (value.length() > 0) {
                mSetting1.setText(value);
                String dateVal = mSetting2.getText().toString();
                if (!"日期".equals(dateVal)) {
                    getData(dateVal, value);
                } else {
                    Date date = new Date();
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
                    getData(format.format(date), value);
                }
            }
        }
    }

    /**
     * 设置监听器
     */
    private void setListener() {
        mListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int index,
                                    long arg3) {
                AssayModel model = mData.get(index);
                Intent i = new Intent(getActivity(), MyFragmentActivity.class);
                i.putExtra("flag", "assayDetail");
                i.putExtra("saverId", model.assayId);
                i.putExtra("cargoname", model.cargoName);
                startActivity(i);
            }
        });

/*		mRefresh.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mSetting1.setText("货名");
				mSetting2.setText("日期");
				Date date = new Date();
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
				getData(format.format(date), "");
			}
		});*/
    }

    private void setAdapter() {
        mAdapter = new MyBaseAdapter();
        mListView.setAdapter(mAdapter);
    }

    /**
     * 获取数据
     */
    private void getData(String date, String cargoName) {
        mListView.setVisibility(View.GONE);
        mTipView.setVisibility(View.GONE);
        mProgress.setVisibility(View.VISIBLE);
        String methodName = "getAllAssay";
        ArrayList<String> param = new ArrayList<>();
        ArrayList<String> value = new ArrayList<>();
        param.add("time");
        param.add("cargoname");
        value.add(date);
        value.add(cargoName);
        Listener<String> listener = new Listener<String>() {

            @SuppressWarnings({"unchecked", "static-access"})
            @Override
            public void onResponse(String response) {

                mProgress.setVisibility(View.GONE);
                String value = JsonHelper.getJsonStrFromNetData(response);
                mData = (List<AssayModel>) AbJsonUtil.fromJson(value,
                        new TypeToken<ArrayList<AssayModel>>() {
                        });

                if (mData == null) {
                    mData = new ArrayList<>();
                }
                if (mData.size() == 0) {
                    mListView.setVisibility(View.GONE);
                    mTipView.setVisibility(View.VISIBLE);
                    mTipView.setText("没有查询到数据");
                } else {
                    mListView.setVisibility(View.VISIBLE);
                    mTipView.setVisibility(View.GONE);
                }
                mAdapter.notifyDataSetChanged();
            }
        };

        ErrorListener errorListener = new ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mListView.setVisibility(View.GONE);
                mProgress.setVisibility(View.GONE);
                mTipView.setVisibility(View.VISIBLE);
                mTipView.setText("获取数据出现异常:" + error.toString());
            }
        };

        VolleyCallWebService httpService = new VolleyCallWebService(methodName,
                param, value, listener, errorListener, Priority.NORMAL);
        VolleySingleton volley = VolleySingleton.getVolleyInstance(getActivity());
        volley.addRequest(httpService);
    }

    class MyBaseAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return mData.size();
        }

        @Override
        public Object getItem(int position) {
            return mData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                holder = new ViewHolder();
//                LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(getActivity().LAYOUT_INFLATER_SERVICE);
                convertView = View.inflate(getActivity(), R.layout.assay_list_item, null);
                holder.mImg = convertView.findViewById(R.id.assay_list_item_ico);
                holder.mTxt = convertView.findViewById(R.id.assay_list_item_content);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            AssayModel model = mData.get(position);
            String builder = "化验编号:" +
                    (model.assayId == null ? "" : model.assayId) +
                    "  |货名:" +
                    (model.cargoName == null ? "" : model.cargoName) +
                    "  |单价:" +
                    (model.price == null ? "" : model.price) +
                    "  |扣杂:" +
                    (model.kouZa == null ? "" : model.kouZa) +
                    "  |扣水:" +
                    (model.kouShui == null ? "" : model.kouShui);

            holder.mTxt.setText(builder);
            return convertView;
        }

        class ViewHolder {
            ImageView mImg;
            TextView mTxt;
        }

    }
}
